package com.ruoyi.common.config;

import com.ruoyi.common.mqtt.MqttSSLUtils;
import com.ruoyi.common.mqtt.OnMessageCallback;
import com.ruoyi.common.mqtt.YuMqttClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Duke_yzl
 * @date 20230605.01
 * @describe：MQTT订阅  回调地址涉及到redis使用DependsOn注解优先加载redis工具类
 */
@Slf4j
@Configuration
@ConfigurationProperties("mqtt")
@Data
//@DependsOn("redisUtils")
public class MqttConfig {

    private String host;
    private String clientId;
    private String[] topic;
    private Integer qos;
    private String username;
    private String password;
    private Integer timeout;
    private Integer keepalive;


    @Bean
    public YuMqttClient mqttClient(){
        try {
            YuMqttClient client = new YuMqttClient(host, clientId, new MemoryPersistence());
            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(username);
            connOpts.setPassword(password.toCharArray());
            // 保留会话
            connOpts.setCleanSession(false);
            // 设置CA证书
            try {
                String caCrtFile = "mqtt/emqxsl-ca.crt";
                connOpts.setSocketFactory(MqttSSLUtils.getSingleSocketFactory(caCrtFile));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            // 设置回调
            client.setCallback(new OnMessageCallback(client));

            // 建立连接
            log.info("Connecting to broker: " + host);
            client.connect(connOpts);

            log.info("连接成功");
            int[] qoss = new int[topic.length];
            for (int i = 0; i < topic.length; i++) {
                qoss[i] = qos;
            }
            // 订阅
            client.subscribe(topic,qoss);
            return client;
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }

    }


}

